<?php
/**
 * Created by PhpStorm.
 * User: tandunzhao
 * Date: 2017/11/20
 * Time: 下午5:26
 */

namespace App\Console\Commands;

use App\Modules\Agent\Services\AgentServices;
use App\Modules\BackCost\Models\HbGzh;
use App\Modules\BackCost\Services\HbGzhsServices;
use App\Modules\BackCost\Models\HbMonthStats;
use App\Modules\BackCost\Services\HbMonthStatsServices;
use App\Modules\Channel\Services\ChannelDailyStatService;
use App\Modules\SendOrder\Models\SendOrder;
use App\Modules\SendOrder\Services\SendOrderService;
use App\Modules\Trade\Services\OrderService;
use App\Modules\User\Models\UserSubscribeBehaviorStats;
use DB;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Log;

class BackCostModel extends Command
{
    /**
     * 执行命令 获取站点的派单数据及服务号信息
     *
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'generate_hb_month_stats';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '服务号回本模型';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $start_date = date('Y-m-01',strtotime('-1 month'));
        $end_date = date('Y-m-d',strtotime(date('Y-m-01').' -1 day'));
        $promotion_gzhs = HbGzhsServices::getSearch([]);


        foreach ($promotion_gzhs as $key=>$promotion_gzh) {
            $cost = 0;                      //成本
            $new_subscribe =    0;          //新关
            $actual_subscribe = 0;          //净关
            $accumulative_actual_subscribe = 0;  //累计净关
            $cancel_subscribe = 0;          //取关
            $total_recharge =   0;          //充值 = 广告收入 + 服务号充值 + 推其它网站充值
            $advertise_income = 0;          //广告收入
            $account_recharge = 0;          //服务号充值
            $outside_recharge = 0;          //推其它网站充值
            $user_subscribe =  UserSubscribeBehaviorStats::whereBetween('date',[$start_date,$end_date])
                ->select([
                    DB::raw('sum(yesterday_actual_new_user) as new_subscribe_sum'),
                    DB::raw('sum(yesterday_actual_sub_num) as actual_sub_num'),
                    DB::raw('sum(recharge_sum) as recharge_sum')
                ])
                ->where('appid',$promotion_gzh->appid)
                ->first();
            $new_subscribe = $user_subscribe->new_subscribe_sum?$user_subscribe->new_subscribe_sum:0;
            $actual_subscribe =$user_subscribe->actual_sub_num?$user_subscribe->actual_sub_num:0;
            $account_recharge = $user_subscribe->recharge_sum?$user_subscribe->recharge_sum:0;
            $total_recharge = $account_recharge+$advertise_income+$outside_recharge;
            $user_cumulate = self::getOfficialAccountFansNum($user_subscribe->appid,$end_date,$end_date);
            if(isset($user_cumulate['user_cumulate']['list']) && count($user_cumulate['user_cumulate']['list'])>0){
                $accumulative_actual_subscribe =  $user_cumulate['user_cumulate']['list'][0]['cumulate_user'];
            }

            $accumulative_info = HbMonthStats::where('appid',$promotion_gzh->appid)->select(DB::raw('sum(total_income) as total_income_sum,sum(cost) as cost_sum'))->first();

            $month = $start_date;
            $to_insert = ['appid'=>$promotion_gzh->appid,'month'=>$month];
            $to_update = [
                'advertise_income'=>$advertise_income,'sub_user_num'=>$new_subscribe,
                'actual_sub_num'=>$actual_subscribe,'accum_actual_sub_num'=>$accumulative_actual_subscribe,
                'cancel_sub_num'=>($new_subscribe-$actual_subscribe),'total_income'=>$total_recharge,
                'account_recharge'=>$account_recharge,'outside_recharge'=>$outside_recharge,
                'accum_recharge_sum'=>$accumulative_info->total_income_sum+$total_recharge,
                'accum_cost_sum'=>$accumulative_info->cost_sum
            ];
            HbMonthStats::updateOrCreate($to_insert,$to_update);
        }

        $lists = HbGzh::where('start_time','<=',$end_date)->where(function($query) use($start_date){
            $query->whereNull('end_time')->orwhere('end_time','>',$start_date);
        })->get();
        $promotion_gzhs_format = [];
        foreach ($lists as $list) {
            if(array_key_exists($list->distribution_channel_id,$promotion_gzhs_format)){
                $promotion_gzhs_format[$list->distribution_channel_id][] = $list;
            }else{
                $promotion_gzhs_format[$list->distribution_channel_id] = [$list];
            }
        }

        foreach($promotion_gzhs_format as $promotion_gzh_format) {
            $cost = SendOrder::whereBetween('pre_send_date',[$start_date,$end_date])
                ->where('distribution_channel_id',$promotion_gzh_format->distribution_channel_id)
                ->sum('cost');
            $new_subscribe_sum =0;
            foreach ($promotion_gzh_format as &$each) {
                $hbMonthStats = HbMonthStatsServices::getOneByAppidMonth($each->appid,$month);
                $new_subscribe_sum += $hbMonthStats->sub_user_num;
                $each->hbstats = $new_subscribe_sum;
            }

            foreach ($promotion_gzh_format as $item){
                $hbMonthStats = $item->hbstats;   //HbMonthStatsServices::getOneByAppidMonth($item->appid,$month);
                //$new_subscribe_sum += $hbMonthStats->sub_user_num;
                $hbMonthStats->cost = ($hbMonthStats->sub_user_num/$new_subscribe_sum)*$cost;
                $hbMonthStats->accum_cost_sum = ($hbMonthStats->sub_user_num/$new_subscribe_sum)*$cost+$hbMonthStats->accum_cost_sum;
                $hbMonthStats->save();
            }
        }
    }

    private static function getOfficialAccountFansNum($appid,$start_date,$end_date){
        $client = New Client(['base_uri' => env('MEDIA_API_BASE_URI')]);
        $response = $client->request('GET','get_gzh_statistics',['query'=>['gzh_app_id'=>$appid,'from_date'=>$start_date,'to_date'=>$end_date]]);
        $res = json_decode($response->getBody(),true);
        //if(isset($res['']))
        return $res['data'];
    }
}